#include <iostream>
#include <unistd.h>
#include <cstdio>
#include <vector>
#include <sys/types.h>
#include <sys/wait.h>
#include <string>

enum{
  OK = 0,
  OPEN_FILE_ERROE = 1,
};


const std::string gsep = " ";

std::vector<int> data;

int SaveBegin()
{
    std::string name = std::to_string(time(nullptr));
    name += ".backup";
    FILE* fp = fopen(name.c_str(),"w");
    if(fp == nullptr)
      return OPEN_FILE_ERROE;
    
    std::string dataStr;
    for(auto d : data)
    {
      dataStr += std::to_string(d);
      dataStr += gsep;
    }
  
    fputs(dataStr.c_str(),fp);
   fclose(fp);
    return OK;
}
void Save()
{
  pid_t id = fork();
  if(id == 0)
  {
    //子进程
    int code = SaveBegin();
    exit(code);
  }
  int status = 0;
  pid_t rid = waitpid(id,&status,0);
  if(rid > 0)
  {
    int code = WEXITSTATUS(status);
    if(code == 0)
      printf("备份成功!,exit code:%d\n",WEXITSTATUS(status));
    else 
      printf("备份失败!,exit code:%d\n",WEXITSTATUS(status));
  }
  else{
    perror("waitpid");
  }

}

int main()
{
  srand(time(nullptr));
  int cnt = 1;
  while(true)
  {
    data.push_back(cnt++);
    sleep(1);

    if(cnt % 10 == 0)
    {
      //每隔十秒备份一次
      Save();
    }
  }
}
